package com.fatgirl.interactive.img
{
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.InteractiveObject;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.utils.Dictionary;

	/**
	 * 不透明区域检查处理 
	 * 
	 * 调用静态方法 setContainer 设置检测容器后
	 * 实现了 IOpaqueTest接口的 类对象被点击到非透明区域后 会触发 IOpaqueTest接口的clickHandler 方法
	 * @author iceman
	 * 
	 */
	public class OpaqueTestManager
	{
		private static var s_container:DisplayObjectContainer;
		private static var s_matrix:Matrix = new Matrix;
		private static var s_bitmapData:BitmapData = new BitmapData(1,1,true,0);

		public static function setContainer(_container:DisplayObjectContainer):void
		{
			if(s_container) s_container.removeEventListener(MouseEvent.CLICK,mouseClickHandler);
			s_container = _container;
			s_container.addEventListener(MouseEvent.CLICK,mouseClickHandler);
		}
		private static function mouseClickHandler(e:MouseEvent):void
		{
			var t_container:DisplayObjectContainer = e.currentTarget as DisplayObjectContainer;
			var t_arr:Array = t_container.getObjectsUnderPoint(new Point(t_container.mouseX,t_container.mouseY));
			var t_len:int = t_arr.length;
			while(t_len--)
			{
				var t_IOpaqueTest:IOpaqueTest = findTestType(t_arr[t_len]);
				if(getTestResult(t_IOpaqueTest as DisplayObject))
				{
					t_IOpaqueTest.clickHandler(e);
					break;
				}
			}
		}
		private static function findTestType(_disObj:DisplayObject):IOpaqueTest
		{
			while(_disObj)
			{
				if(_disObj is IOpaqueTest) return _disObj as IOpaqueTest;
				_disObj = _disObj.parent;
			}
			return null;
		}
		private static function getTestResult(_disObj:DisplayObject):Boolean
		{
			if(!_disObj) return false;
			s_matrix.tx = -_disObj.mouseX;
			s_matrix.ty = -_disObj.mouseY;
			s_bitmapData.setPixel32(0,0,0);
			s_bitmapData.draw(_disObj,s_matrix);
			if(s_bitmapData.getPixel32(0,0)>10) return true;
			return false;
		}
	}
}